package com.example.springboot01.controller;

import com.example.springboot01.pojo.Managers;
import com.example.springboot01.service.ManagersService;
import com.example.springboot01.utils.Md5Encrypt;
import com.example.springboot01.utils.UUidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/manage/test")
@CrossOrigin  // 解决跨域问题
public class ManagersTest {

    @Autowired
    private ManagersService managersService;

    @PostMapping("/addManagers")
    public Map<String, Object> addManagers(@RequestBody Managers managers) {
        Map<String, Object> map = new HashMap<>();

        // 检查密码是否为空
        String password = managers.getPassw();
        if (password == null || password.isEmpty()) {
            map.put("status", 0);
            map.put("msg", "密码不能为空");
            return map;  // 直接返回，不执行 md5
        }

        // 安全地加密密码
        managers.setPassw(Md5Encrypt.md5(password));

        // 设置其他字段
        managers.setUid(UUidUtils.getUUID());
        managers.setState(2);

        // 插入数据库
        int re = managersService.insertManagers(managers);
        if (re > 0) {
            map.put("status", 1);
        } else {
            map.put("status", 0);
            map.put("msg", "添加管理员失败");
        }

        return map;
    }

    @RequestMapping("/editManagers")
    public Map<String,Object> editManagers(Managers managers)
    {
        Map<String,Object> map = new HashMap<String,Object>();
        managers.setPassw(Md5Encrypt.md5(managers.getPassw()));
        int re = managersService.updateManagers(managers);
        if(re>0)
        {
            map.put("status", 1);
        }else {
            map.put("status", 0);
        }
        return map;
    }

    @RequestMapping("/getManagersByuid")
    public Map<String,Object> getManagers(String uid)
    {
        Map<String,Object> map = new HashMap<String,Object>();
        Managers managers = managersService.getManagersByUid(uid);
        map.put("managers", managers);
        return map;
    }

    @RequestMapping("/getList")
    public Map<String,Object> getList()
    {
        Map<String,Object> map = new HashMap<String,Object>();
        Managers actorsManagers = new Managers();
        actorsManagers.setState(1);
        List<Managers> allmanagers = managersService.getList(actorsManagers);
        map.put("allmanagers", allmanagers);
        return map;
    }


}
